package com.zy.web.controller.business;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zy.business.domain.*;
import com.zy.business.mapper.*;
import com.zy.business.service.PunchCardService;
import com.zy.business.service.ShiftService;
import com.zy.common.core.controller.BaseController;
import com.zy.common.core.domain.AjaxResult;
import com.zy.common.core.domain.entity.SysUser;
import com.zy.common.utils.DateUtil;
import com.zy.common.utils.SecurityUtils;
import com.zy.common.utils.StringUtils;
import com.zy.system.service.ISysRoleService;
import com.zy.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description: 首页接口
 * @author: whf
 * @create: 2023-02-27 09:48
 **/
@Api(tags = "首页接口")
@RestController
@RequestMapping("/index")
public class IndexController extends BaseController {

    @Resource
    private AbsenceMapper absenceMapper;

    @Resource
    private AbsenceAuditMapper absenceAuditMapper;

    @Resource
    private ReissueCardMapper reissueCardMapper;

    @Resource
    private OverworkAuditMapper auditMapper;

    @Resource
    private ReportUserMapper reportUserMapper;

    @Resource
    private VisitorRecordMapper visitorRecordMapper;

    @Resource
    private ProjectMapper projectMapper;

    @Resource
    private OverworkMapper overworkMapper;

    @Resource
    private WorkReportMapper workReportMapper;

    @Resource
    private ProjectFollowMapper followMapper;

    @Resource
    private PunchCardMapper punchCardMapper;

    @Autowired
    private PunchCardService punchCardService;

    @Autowired
    private ShiftService tbShiftService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @ApiOperation(value = "获取待办事项")
    @GetMapping("/getNotHandle")
    public AjaxResult getNotHandle() {
        Long userId = SecurityUtils.getUserId();
        Map<String, Object> map = new HashMap<>();
        Long absenceNum = absenceAuditMapper.getAuditCount(userId);
        map.put("absenceNum",absenceNum);
        Long reissueNum = reissueCardMapper.selectCount(new QueryWrapper<TbReissueCard>().eq("audit_user_id", userId).eq("status", 0));
        map.put("reissueNum",reissueNum);
        int overworkNum = auditMapper.getAuditCount(userId);
        map.put("overworkNum",overworkNum);
        Long noReadNum = reportUserMapper.getNoReadCount(userId);
        map.put("noReadNum",noReadNum);
        /*Long visitorNum = visitorRecordMapper.selectCount(new QueryWrapper<TbVisitorRecord>().eq("visit_user_id", userId).eq("state", 0));*/
        map.put("visitorNum",0);
        return AjaxResult.success(map);
    }

    @ApiOperation(value = "获取我的项目type:1月2季度3年")
    @GetMapping("/getMyProject")
    public AjaxResult getMyProject(@RequestParam Integer type){
        Long userId = SecurityUtils.getUserId();
        List<Map<String,Object>> dataList = projectMapper.getMyProject(userId,type);
        return AjaxResult.success(dataList);
    }

    @ApiOperation(value = "获取我的申请type:1月2季度3年")
    @GetMapping("/getMyApply")
    public AjaxResult getMyApply(@RequestParam Integer type){
        Long userId = SecurityUtils.getUserId();
        Map<String,Object> absenceMap = absenceMapper.getAbsenceData(userId,type);
        Map<String,Object> overWorkMap = overworkMapper.getOverWorkData(userId,type);
        Map<String,Object> reissueCardMap = reissueCardMapper.getReissueCardData(userId,type);
        int noAuditNum = Integer.valueOf(absenceMap.get("noAuditNum").toString()) + Integer.valueOf(overWorkMap.get("noAuditNum").toString()) + Integer.valueOf(reissueCardMap.get("noAuditNum").toString());
        int agreeNum = Integer.valueOf(absenceMap.get("agreeNum").toString()) + Integer.valueOf(overWorkMap.get("agreeNum").toString()) + Integer.valueOf(reissueCardMap.get("agreeNum").toString());
        int refuseNum = Integer.valueOf(absenceMap.get("refuseNum").toString()) + Integer.valueOf(overWorkMap.get("refuseNum").toString()) + Integer.valueOf(reissueCardMap.get("refuseNum").toString());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("noAuditNum", noAuditNum);
        map.put("agreeNum", agreeNum);
        map.put("refuseNum", refuseNum);
        return AjaxResult.success(map);
    }

    @ApiOperation(value = "获取工作汇报type:1月2季度3年")
    @GetMapping("/getWorkReport")
    public AjaxResult getWorkReport(@RequestParam Integer type){
        Long userId = SecurityUtils.getUserId();
        Map<String,Object> dataMap = workReportMapper.getWorkReport(userId,type);
        return AjaxResult.success(dataMap);
    }

    @ApiOperation(value = "获取项目负责人下拉框数据")
    @GetMapping("/getPrincipalOption")
    public AjaxResult getPrincipalOption(){
        List<Map<String,Object>> options = projectMapper.getPrincipalOption();
        return AjaxResult.success(options);
    }

    @ApiOperation(value = "获取客户更进")
    @GetMapping("/getProjectFollow")
    public AjaxResult getProjectFollow(Long userId){
        String userName = "";
        if(userId!=null) {
            SysUser sysUser = userService.selectUserById(userId);
            userName = sysUser.getUserName();
        }
        List<Map<String,Object>> dataList = followMapper.getProjectFollowData(userName);
        String[] monthArr = new String[12];
        Integer[] dataArr = new Integer[12];
        for (int i = 0; i < 12; i++) {
            monthArr[i] = (i+1) + "月";
            dataArr[i] = 0;
            if (dataList!=null && dataList.size() > 0) {
                for (Map<String, Object> map : dataList) {
                    if ((i+1)== Integer.parseInt(map.get("createMonth").toString())){
                        dataArr[i] = Integer.parseInt(map.get("num").toString()) ;
                    }
                }
            }
        }
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("monthArr",monthArr);
        dataMap.put("dataArr",dataArr);
        return AjaxResult.success(dataMap);
    }

    @ApiOperation(value = "获取我的考勤")
    @GetMapping("/getMyAttendance")
    public AjaxResult getMyAttendance(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm");
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TbShift shift = tbShiftService.selectTbShiftById();
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("shift",shift);
        Long userId = SecurityUtils.getUserId();
        String startTime = "";
        String endTime = sdf.format(new Date());
        String msg = "";
        try {
            Set<String> roles = roleService.selectRolePermissionByUserId(userId);
            if (SecurityUtils.isAdmin(userId) || roles.contains("manager")){
                List<Map<String,Object>> list = punchCardService.selectTodayAttendance(new SysUser());
                dataMap.put("todayAttendance",list);
            }else {
                List<Map<String, Object>> todayList = punchCardMapper.selectMyAttendance(userId,sdf.format(new Date()));
                dataMap.put("todayList",todayList);
                for (int k = 0; k < 2; k++) {
                    if (k==0){
                        startTime = sdf.format(DateUtil.getFirstDayOfWeek());
                    }
                    if (k==1){
                        startTime = DateUtil.getMonthStart();
                    }
                    Map<String,Object> punchCardMap = punchCardMapper.getMyAttendance(userId, startTime, endTime);
                    List<TbAbsence> absenceList = absenceMapper.getUserList(userId,startTime,endTime);
                    List<TbOverwork> overworkList = overworkMapper.selectList(new QueryWrapper<TbOverwork>().eq("apply_id", userId).between("DATE(START_TIME)", startTime, endTime).eq("status", 2));
                    Double absenceTotal = 0d;
                    Double overworkTotal = 0d;
                    if(absenceList!=null && absenceList.size()>0){
                        for(TbAbsence absence:absenceList){
                            Double everyAbsence = 0d;
                            if(sdf.format(absence.getStartTime()).equals(sdf.format(absence.getEndTime()))){
                                everyAbsence += absence.getAbsenceDuration();
                            }else{
                                Double absenceDuration = 0d;
                                //判断请假开始时间
                                if(shift.getStartTime1().compareTo(sdf2.format(absence.getStartTime()))>=0){
                                    everyAbsence += 7.5d;
                                }else if(shift.getStartTime1().compareTo(sdf2.format(absence.getStartTime()))<0 && shift.getEndTime1().compareTo(sdf2.format(absence.getStartTime()))>0){
                                    Date date1 = sdf3.parse(sdf.format(absence.getStartTime())+ " 11:30:00");
                                    long diff = date1.getTime()-absence.getStartTime().getTime();
                                    double hours = (double)diff / (1000 * 60 * 60);
                                    everyAbsence += hours+4.5;
                                }else if(shift.getStartTime2().compareTo(sdf2.format(absence.getStartTime()))==0){
                                    everyAbsence += 4.5;
                                }else if(shift.getStartTime2().compareTo(sdf2.format(absence.getStartTime()))<0 && shift.getEndTime2().compareTo(sdf2.format(absence.getStartTime()))>0){
                                    Date date1 = sdf3.parse(sdf.format(absence.getStartTime())+ " 18:00:00");
                                    long diff = date1.getTime()-absence.getStartTime().getTime();
                                    double hours = (double)diff / (1000 * 60 * 60);
                                    everyAbsence += hours;
                                }
                                //给请假结束日期赋值小时数
                                Double endAbsenceDuration = 0d;
                                BigDecimal b1 = new BigDecimal(absence.getAbsenceDuration().toString());
                                BigDecimal b2 = new BigDecimal(absenceDuration.toString());
                                Double diffHours = new Double(b1.subtract(b2).doubleValue());
                                Double d = diffHours%7.5;
                                Double a = diffHours/7.5;
                                int b = a.intValue();
                                if(d==0){
                                    endAbsenceDuration = 7.5;
                                }else{
                                    endAbsenceDuration = d;
                                }
                                if(b>=1){
                                    int i=1;
                                    String date = sdf.format(absence.getStartTime());
                                    while (i<b){
                                        date = DateUtil.addDay(date);
                                        if(sdf.parse(date).getTime()>sdf.parse(endTime).getTime()){
                                            break;
                                        }
                                        everyAbsence += 7.5d;
                                        i++;
                                    }
                                    if(absence.getEndTime().getTime()<=sdf.parse(endTime).getTime()){
                                        everyAbsence += endAbsenceDuration;
                                    }
                                }

                            }
                            absenceTotal += everyAbsence;
                        }
                    }
                    if (overworkList!=null && overworkList.size()>0){
                        for (TbOverwork overwork : overworkList) {
                            overworkTotal += overwork.getWorkHour();
                        }
                    }
                    if (punchCardMap!=null){
                        if (k==0){
                            if (!"0".equals(punchCardMap.get("defectNum").toString())){
                                msg += "，缺卡"+punchCardMap.get("defectNum").toString()+"次";
                            }
                            if (!"0".equals(punchCardMap.get("lateNum").toString())){
                                msg += "，迟到"+punchCardMap.get("lateNum").toString()+"次";
                            }
                            if (absenceTotal!=0d){
                                msg += "，请假"+absenceTotal+"小时";
                            }
                            if (overworkTotal!=0d){
                                msg += "，加班"+overworkTotal+"小时";
                            }
                            if (StringUtils.isEmpty(msg)){
                                msg = "考勤正常，您辛苦了~";
                            }else {
                                msg = msg.substring(1);
                            }
                            dataMap.put("weekAttendance",msg);
                        }
                        if (k==1){
                            dataMap.put("monthDefectNum",punchCardMap.get("defectNum"));
                            dataMap.put("monthLateNum",punchCardMap.get("lateNum"));
                            dataMap.put("monthOverwork",overworkTotal);
                            dataMap.put("monthAbsence",absenceTotal);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(dataMap);
    }

}
